from flask_wtf import FlaskForm
from wtforms import StringField,PasswordField,BooleanField,SubmitField,IntegerField
from wtforms.validators import DataRequired,Length,InputRequired,ValidationError,NumberRange


class BaseForm(FlaskForm):
    class Meta:
        #强制指定为中文 要配合 imdb_app.config['WTF_I18N_ENABLED'] = False 来使用
        locales = ['zh']

#定义校验器函数
def is_adult(form,field):
    if field.data < 18:
        raise ValidationError("不是成年人")

def is_adult_factory(message=None):
    if not message:
        message = '不是成年人'
    def is_adult(form,field):
        if field.data < 18:
            raise ValidationError(message)
    return is_adult

class LoginForm(BaseForm):
    #通过 render_kw 可以传入html相关标签属性
    #username = StringField('用户名',validators=[InputRequired(message="用户名不能为空")],render_kw={"class":"form-control"})
    username = StringField('用户名',validators=[InputRequired(message="用户名不能为空")])
    password = PasswordField('密码',validators=[DataRequired("密码不能为空"),Length(8,20,message="密码长度为8-20")])
    mark = StringField('备注',validators=[Length(8,20)])
    age = IntegerField('年龄',validators=[NumberRange(1,120),is_adult_factory("不是中国法定成年人")])
    remember = BooleanField("记住我")
    submit = SubmitField("登录")

    # 规范要求, validate开头的方法WTForms 会自动调用来校验
    def validate_age(self,field):
        if field.data < 15:
            raise ValidationError("不满15岁不得注册")